package repository

import (
	"booksmart/book/internal/domain"
	"booksmart/book/internal/repository/cache"
	"context"
)

type RankingRepository interface {
	ReplaceTopN(ctx context.Context, arts []domain.Article) error
	GetTopN(ctx context.Context) ([]domain.Article, error)
}

type CacheRankingRepository struct {
	redis cache.RankingCache
	local *cache.RankingLocalCache
}

func NewCacheRankingRepository(redis cache.RankingCache, local *cache.RankingLocalCache) *CacheRankingRepository {
	return &CacheRankingRepository{redis: redis, local: local}
}

func (c CacheRankingRepository) ReplaceTopN(ctx context.Context, arts []domain.Article) error {
	_ = c.local.Set(ctx, arts)
	return c.redis.Set(ctx, arts)
}

func (c CacheRankingRepository) GetTopN(ctx context.Context) ([]domain.Article, error) {
	data, err := c.local.Get(ctx)
	if err == nil {
		return data, err
	}
	data, err = c.redis.Get(ctx)
	if err == nil {
		_ = c.local.Set(ctx, data)
	} else {
		//强制使用本地缓存，防止redis崩溃，增加可用性。
		data, err = c.local.ForceGet(ctx)
	}
	return data, err
}
